<template>
  <com-page ref="page" :showFloatingNav="false" :paddingBottom="'312rpx'" :showCustomer="false">
    <view class="body">
      <img
        class="bg-img"
        src="https://ainengli.meilianshuke.com/jkhx/raozg/upload-bg.png"
        alt=""
      />
      <view class="header-info">
        <view class="info-top">{{ doctorInfo.name }}医生邀请您</view>
        <view class="info-top">上传就诊数据</view>
        <view class="info-bottom">上传后，医生可查看您的相关资料</view>
      </view>
      <view class="card">
        <view class="title">
          <view class="line" />
          <text>医生信息</text>
        </view>
        <view class="doctor-info" v-if="doctorInfo">
          <view style="display: flex">
            <img v-if="doctorInfo.avatar" class="avatar-img" :src="doctorInfo.avatar" alt="" />
            <img
              v-else-if="doctorInfo.gender == 2"
              class="avatar-img"
              src="https://ainengli.meilianshuke.com/jkhx/raozg/doctor-female.png"
              alt=""
            />
            <img
              v-else
              class="avatar-img"
              src="https://ainengli.meilianshuke.com/jkhx/raozg/doctor-male.png"
              alt=""
            />
            <view class="middle-info">
              <view class="top">
                <text class="name">{{ doctorInfo.name }}</text>
                <text class="sex">{{ doctorInfo.titleName }}</text>
              </view>
              <view class="bottom">
                <text>{{ doctorInfo.hospitalName }}</text>
                <text style="margin-left: 16rpx">{{
                  doctorInfo.departmentName
                }}</text>
              </view>
            </view>
          </view>
          <view
            @tap="follow"
            :class="['follow-btn', doctorStatus ? 'follow-btn-active' : '']"
          >
            {{ doctorStatus ? "已关注" : "关注TA" }}
          </view>
        </view>
      </view>
      <view class="card">
        <view @tap="show = true" class="cell">
          <view class="label">选择就诊人</view>
          <view class="values">
            <text>{{ selectInfo?.patientName }}</text>
            <image
              class="img_more"
              src="https://ainengli.meilianshuke.com/jkhx/raozg/more.png"
            />
          </view>
        </view>
      </view>
      <view class="card" style="padding-bottom: 0">
        <view class="title">
          <view class="line" />
          <text>当前身高体重</text>
        </view>
        <!-- <view class="cell">
          <view class="label"><text style="color: red">*</text>当前身高</view>
          <view class="values">
            <input
                type="digit"
                class="form_input pop_input"
                v-model="heightAndweight.height"
                placeholder="请输入"
                :border="false"
            />
            <text>cm</text>
          </view>
        </view>
        <view class="cell">
          <view class="label"><text style="color: red">*</text>当前体重</view>
          <view class="values">
            <input
                type="digit"
                class="form_input pop_input"
                v-model="heightAndweight.weight"
                placeholder="请输入"
                :border="false"
            />
            <text>kg</text>
          </view>
        </view> -->
        <com-form v-if="!loading" ref="myForm">
          <com-form-item
            v-model="heightAndweight.height"
            label="当前身高"
            labelWidth="180rpx"
            required
            unit="cm"
            placeholder="请输入"
            inputType="number"
            :precision="1"
          />
          <com-form-item
            v-model="heightAndweight.weight"
            label="当前体重"
            labelWidth="180rpx"
            required
            unit="kg"
            placeholder="请输入"
            inputType="number"
            :precision="1"
          />
        </com-form>
      </view>
      <view class="card">
        <view class="title">
          <view class="line" />
          <text>病历或报告图片</text>
          <text class="upload-tips">(请上传一份病历，最多5图片)</text>
        </view>
        <com-upload-images
          v-model="fileUrls"
          :page="imagePage"
          :maxlength="5"
        />
      </view>
      <com-popup
        v-if="show"
        ref="popup"
        title="选择就诊人"
        :bottom="32"
        :action="false"
        :showTitleBorder="true"
        @close="show = false"
      >
        <view class="lists">
          <view
            v-for="(item, index) in patientList"
            :key="index"
            :class="['item', item.id == selectInfo.id ? 'active' : '']"
            @tap="selectPatient(item)"
          >
            <view>{{ item?.patientName }}</view>
            <view class="info">
              <text class="gender">{{ item.gender == 1 ? '男' : '女' }}</text>
              <text>{{ item.ageYear > 0 ? item.ageYear + '岁' : '' }}{{ item.ageMonth == 0 && item.ageYear == 0 ? '未满月' : item.ageYear < 18 && item.ageMonth != 0 ? item.ageMonth + '月' : '' }}
              </text>
            </view>
            <image v-show="item.id === store.patient.current.id" src="https://ainengli.meilianshuke.com/jkhx/patient/selected-icon.png" class="selected" />
          </view>
        </view>
      </com-popup>
      <view class="fixed">
        <button class="confirm_btn" @tap="save">上传</button>
      </view>
    </view>
  </com-page>
</template>

<script setup lang="ts">
import { ref, reactive, getCurrentInstance, computed, nextTick } from "vue";
import { getPatientList } from "@/request/apis/patient.js";
import {
  getDoctorInfo,
  getSceneInfo,
  getDoctorAttention,
  addDoctorAttention,
  deleteDoctorAttention,
  saveHealthRecord,
} from "./follows.api";
import { onShow, onLoad, onReady } from "@dcloudio/uni-app";
import { debounce } from "@/uni_modules/lime-shared/debounce";

const { proxy }: any = getCurrentInstance();

const userInfo = ref<any>();
const heightAndweight = reactive({
  height: "",
  weight: "",
});
const show = ref(false);
const selectInfo = ref({});
const patientList = computed(() => proxy.store.patient.list);
const doctorInfo = ref<any>();

const doctorStatus = ref<boolean>(false);

const sceneId = ref();
const sceneData = ref();
const imagePage = ref(null);
const fileUrls = ref([]);
const isFirstShow = ref(false)

onLoad((e) => {
  uni.hideHomeButton();
  if (e && e.scene) {
    sceneId.value = e.scene;
    console.log("医生id", e.scene);
  } else {
    sceneId.value = null;
  }
  //   getDoctor();
  userInfo.value = uni.getStorageSync("system-userinfo")
    ? uni.getStorageSync("system-userinfo")
    : {};
  console.log(userInfo.value, "userInfo");
});

onShow(() => {
  nextTick(() => {
    getSceneInfo({
      scene: sceneId.value,
    }).then((res) => {
      console.log(res);
      sceneData.value = res;
      if (isFirstShow.value) {
        checkPatient()
      }
      isFirstShow.value = true
      getDoctor();
      getDoctorStatus();
    });
  });
  console.log('有就诊人么', selectInfo.value, JSON.stringify(selectInfo.value) === "{}", patientList.value)
  if (JSON.stringify(selectInfo.value) === "{}") {
    patientList.value.forEach((item) => {
        if (item.defaultPatient == 1) {
            selectInfo.value = item;
        }
    });
  }
});

const checkPatient = () => {
  console.log('检查就诊人', selectInfo.value, JSON.stringify(selectInfo.value) === "{}")
  if (JSON.stringify(selectInfo.value) === "{}" && userInfo.value.userId) {
    uni.showModal({
      title: "提示",
      content: "请添加就诊人",
      showCancel: false,
      confirmText: "去添加",
      success: function (res) {
        proxy.utils.uni.route.go("/pages/patients/addOrDelete?type=add");
      },
    });
  }
};

// onReady(() => {
//   if (JSON.stringify(selectInfo.value) === "{}" && userInfo.value.userId) {
//     uni.showModal({
//       title: "提示",
//       content: "请添加就诊人",
//       showCancel: false,
//       confirmText: "去添加",
//       success: function (res) {
//         proxy.utils.uni.route.go("/pages/patients/addOrDelete?type=add");
//       },
//     });
//   }
// });

// 查询关注状态
function getDoctorStatus() {
  getDoctorAttention({
    doctorUserId: sceneData.value.doctorUserId,
  }).then((res) => {
    doctorStatus.value = res;
  });
}

const selectPatient = (item: any) => {
  selectInfo.value = item;
  console.log("切换用户", item, selectInfo.value);
  show.value = false;
};
const getDoctor = () => {
  getDoctorInfo({ doctorUserId: sceneData.value.doctorUserId }).then((res) => {
    doctorInfo.value = res;
  });
};
const follow = () => {
  if (doctorStatus.value) {
    // 取消关注
    deleteDoctorAttention({
      doctorUserId: doctorInfo.value.doctorUserId,
    }).then(() => {
      doctorStatus.value = false;
      proxy.utils.uni.toast("已取消关注");
    });
  } else {
    // 关注
    addDoctorAttention({
      doctorUserId: doctorInfo.value.doctorUserId,
      userId: proxy.store.userInfo.id,
      patientId: selectInfo.value ? selectInfo.value.id : 0,
      hospitalCode: doctorInfo.value.hospitalCode,
    }).then(() => {
      doctorStatus.value = true;
      proxy.utils.uni.toast("关注成功");
    });
  }
};
const save = () => {
  if (!selectInfo.value.id) {
    proxy.utils.uni.toast("请选择就诊人");
    return;
  }
  if (
    Number(heightAndweight.height) < 20 ||
    Number(heightAndweight.height) > 250
  ) {
    proxy.utils.uni.toast("身高范围20-250cm，请重新输入");
    return;
  }
  if (
    Number(heightAndweight.weight) < 2 ||
    Number(heightAndweight.weight) > 200
  ) {
    proxy.utils.uni.toast("体重范围2-200kg，请重新输入");
    return;
  }
  let heightInfo = {
    type: "basic",
    code: "height",
    value: heightAndweight.height,
  };
  let weightInfo = {
    type: "basic",
    code: "weight",
    value: heightAndweight.weight,
  };
  let params = {
    patientId: selectInfo.value.id,
    basicList: [heightInfo, weightInfo],
    fileUrls: fileUrls.value,
    doctorUserId: sceneData.value.doctorUserId,
    bizAppId: sceneData.value.bizAppId,
  };
  console.log("上传入参", params);
  saveHealthRecord(params).then((res) => {
    uni.showToast({
      title: "上传成功",
      icon: "none",
      duration: 2000,
      success: function () {
        uni.switchTab({
          url: "/pages/archive/index",
        });
      },
    });

    // proxy.utils.uni.route.go('/pages/myFollows/index')
  });
};
</script>

<style lang="scss" scoped>
.body {
  padding: 0 32rpx;
  position: relative;
  padding-top: 298rpx;
  background: #f3f7f8;
  .bg-img {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 512rpx;
    z-index: 1;
  }
  .header-info {
    position: absolute;
    top: 62rpx;
    left: 40rpx;
    z-index: 2;
    .info-top {
      font-family: FZZhengHeiS-EB-GB, FZZhengHeiS-EB-GB;
      font-weight: 700;
      font-size: 48rpx;
      color: #00d1b6;
      margin-bottom: 12rpx;
    }
    .info-bottom {
      margin-top: 12rpx;
      font-weight: 400;
      font-size: 26rpx;
      color: #666666;
    }
  }
  .card {
    position: relative;
    z-index: 2;
    background: #ffffff;
    border-radius: 16rpx;
    padding: 32rpx;
    margin-bottom: 24rpx;
    .title {
      display: flex;
      align-items: center;
      justify-content: flex-start;
      margin-bottom: 24rpx;
      font-size: 36rpx;
      font-weight: 700;
      color: #222;

      .line {
        width: 8rpx;
        height: 36rpx;
        margin-right: 16rpx;
        background: #00d1b6;
        border-radius: 0 8rpx 8rpx 0;
      }
      .upload-tips {
        font-weight: 400;
        font-size: 24rpx;
        color: #666666;
        margin-left: 16rpx;
      }
    }
    .doctor-info {
      margin-top: 24rpx;
      display: flex;
      gap: 24rpx;
      justify-content: space-between;
      align-items: center;
      .avatar-img {
        width: 82rpx;
        height: 82rpx;
        border-radius: 50%;
        margin-right: 24rpx;
      }
      .middle-info {
        font-weight: 400;
        font-size: 28rpx;
        color: #666666;
        max-width: 350rpx;
        .name {
          font-weight: 700;
          font-size: 32rpx;
          color: #222222;
          margin-right: 20rpx;
        }
        // .bottom {
        //     display: -webkit-box;
        //     text-overflow: ellipsis;
        //     -webkit-line-clamp: 2; /* 省略几行写几 */
        //     -webkit-box-orient: vertical;
        // }
      }
      .follow-btn {
        border-radius: 28rpx 28rpx 28rpx 28rpx;
        border: 1rpx solid #00d1b6;
        font-weight: 400;
        font-size: 26rpx;
        color: #00d1b6;
        padding: 0 24rpx;
        height: 56rpx;
        line-height: 56rpx;
        transform: rotateZ(360deg);
      }

      .follow-btn-active {
        border-color: #cfcfcf;
        color: #cfcfcf;
      }
    }
    .cell {
      display: flex;
      align-items: center;
      justify-content: space-between;
      position: relative;
      .label {
        width: 200rpx;
        font-weight: 500;
        font-size: 30rpx;
        color: #222222;
      }
      .values {
        display: flex;
        align-items: center;
        gap: 8rpx;
      }
      .form_input {
        width: 100%;
        border: none;
        text-align: right !important;
        font-weight: 400 !important;
        font-size: 30rpx !important;
        ::v-deep .uni-input-placeholder {
          text-align: right;
          color: #cccccc !important;
        }
        ::v-deep .uni-input-input {
          text-align: right;
          // direction: rtl;
          color: #222 !important;
        }
      }
      .img_more {
        width: 40rpx;
        height: 40rpx;
      }
    }
  }
  .lists {
    padding: 32rpx;
    .item {
      box-sizing: border-box;
      border-radius: 10rpx;
      background: #fafafa;
      // text-align: center;
      display: flex;
      padding: 24rpx;
      font-weight: 500;
      font-size: 32rpx;
      color: #222222;
      margin-bottom: 24rpx;
      gap: 32rpx;
      position: relative;
      .selected {
        position: absolute;
        right: 0;
        top: 0;
        width: 45rpx;
        height: 40rpx;
      }
      .info {
        border: 1rpx solid #e5e6eb;
        border-radius: 4rpx;
        background: #fff;
        padding: 8rpx 24rpx;
        font-size: 24rpx;
        color: #666666;
        .gender::after {
          content: '';
          display: inline-block;
          width: 1rpx;
          height: 18rpx;
          // border-radius: 50%;
          background: #666666;
          margin: 0 16rpx;
        }
      }
    }
    .item.active {
      border: 1rpx solid #00d1b6;
      background: rgba(0, 209, 182, 0.10);
    }
    .item:last-child {
      margin-bottom: 0;
    }
  }
  .fixed {
    position: fixed;
    width: 100%;
    bottom: 0;
    left: 0;
    z-index: 10;
    padding: 24rpx 32rpx;
    padding-bottom: calc(24rpx + constant(safe-area-inset-bottom));
    padding-bottom: calc(24rpx + env(safe-area-inset-bottom));
    box-sizing: border-box;
    background: #ffffff;
    display: flex;
    gap: 24rpx;
    .confirm_btn {
      width: 100%;
      background: #00d1b6;
      border-radius: 44rpx;
      font-weight: 500;
      font-size: 32rpx;
      color: #ffffff;
    }
    button::after {
      border: none;
    }
  }
}
</style>
